package com.syc.config;

import com.syc.entity.Configuration;
import com.syc.entity.MappedStatement;
import com.syc.entity.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 解析mapper.xml
 *
 * @author Shen Yu Chen
 * @create 2020-04-23
 **/
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        //<mapper>
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        //<select>|<insert>|<update>|<delete> 使用"//"从匹配选择的当前节点选择文档中的节点，而不考虑它们的位置
        List<Element> nodes = rootElement.selectNodes("//select|//insert|//update|//delete");
        for (Element node : nodes) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(node.attributeValue("id"));
            mappedStatement.setParamterType(node.attributeValue("paramterType"));
            mappedStatement.setResultType(node.attributeValue("resultType"));
            mappedStatement.setSql(node.getTextTrim());
            if(node.getName().equals("select")){
                mappedStatement.setSqlCommandType(SqlCommandType.SELECT);
            }else if(node.getName().equals("insert")){
                mappedStatement.setSqlCommandType(SqlCommandType.INSERT);
            }else if(node.getName().equals("update")){
                mappedStatement.setSqlCommandType(SqlCommandType.UPDATE);
            }else if(node.getName().equals("delete")){
                mappedStatement.setSqlCommandType(SqlCommandType.DELETE);
            }
            configuration.getMappedStatementMap()
                    .put(namespace+"."+node.attributeValue("id"),mappedStatement);
        }
    }
}
